package cn.com.vs.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import net.coobird.thumbnailator.Thumbnailator;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.log4j.Logger;

import cn.com.vs.Configurator;
import cn.com.vs.utils.PathUtil;

import com.alibaba.fastjson.JSONObject;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;


public class StoreService {
	
	private static Logger logger = Logger.getLogger(StoreService.class);
	private static StoreService inst = new StoreService();
	HttpRequestFactory requestFactory = null;
	JsonFactory JSON_FACTORY = null;
	public static StoreService getInstance(){
		return inst;
	}
	
	protected StoreService(){
		JSON_FACTORY = new JacksonFactory();
		requestFactory = //new NetHttpTransport().createRequestFactory();
				
				new NetHttpTransport().createRequestFactory(new HttpRequestInitializer() {
					@Override
					public void initialize(HttpRequest request) {
						request.setParser(new JsonObjectParser(JSON_FACTORY));
					}
				});
				
	}
	
	public JSONObject reinitServer(String server){
		try{
			GenericUrl  url = new GenericUrl( "http://"+server+"/rebuildIndex");
			HttpRequest request = requestFactory.buildGetRequest(url);
			request.getHeaders().put("OwnerToken", "_DEFAULT_");
			com.google.api.client.http.HttpResponse resp = request.execute();
			int statusCode = resp.getStatusCode();	
			if( statusCode == HttpStatus.SC_OK ){
				JSONObject obj = JSONObject.parseObject(resp.parseAsString());
				return obj;
			}else{
				logger.error("reinitServer faild:status="+statusCode+" msg="+resp.getStatusMessage());
			}
		}catch(Exception e){
			logger.error("reinitServer exception:",e);
		}
		return null;
	}
	
	public String storeImg(String account,String fileName,String base64Data){
		try{
			GenericUrl  url = new GenericUrl(Configurator.getInstance().getString("storeServer")+"/upload");
			url.put("utoken", account);
			url.put("type", "img");
			url.put("file", fileName);
			base64Data = base64Data.replaceAll(" ", "+");
			ByteArrayContent content = new ByteArrayContent(ContentType.APPLICATION_OCTET_STREAM.toString(),Base64.decodeBase64(base64Data));
			HttpRequest request = requestFactory.buildPostRequest(url, content);
			com.google.api.client.http.HttpResponse resp = request.execute();
			int statusCode = resp.getStatusCode();		
			if( statusCode == HttpStatus.SC_OK ){
				JSONObject obj = JSONObject.parseObject(resp.parseAsString());
				boolean flag = obj.getBoolean("ok");
				if( flag ){
					return obj.getString("msg");
				}
				logger.error("storeImg faild:"+obj.getString("msg"));
				return null;
			}else{
				logger.error("storeImg faild:status="+statusCode+" msg="+resp.getStatusMessage());
			}
		}catch(Exception e){
			logger.error("storeImg exception:",e);
		}
		return null;
	}
	
	
	public String storeImgThumb(String account,String fileName,String base64Data,int width,int height){
		try
		{
			base64Data = base64Data.replaceAll(" ", "+");
			GenericUrl  url = new GenericUrl(Configurator.getInstance().getString("storeServer")+"/upload");
			url.put("utoken", account);
			url.put("type", "img");
			String thumbName = PathUtil.getWithoutExtension(fileName)+"_thumb"+PathUtil.getExtension(fileName);
			url.put("file", thumbName);
			byte[] data = Base64.decodeBase64(base64Data);
			InputStream sbs = new ByteArrayInputStream(data);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			Thumbnailator.createThumbnail(sbs, os, width, height);
			ByteArrayContent content = new ByteArrayContent(ContentType.APPLICATION_OCTET_STREAM.toString(),os.toByteArray());
			HttpRequest request = requestFactory.buildPostRequest(url, content);
			com.google.api.client.http.HttpResponse resp = request.execute();
			int statusCode = resp.getStatusCode();;
			if( statusCode == HttpStatus.SC_OK ){
				JSONObject obj = JSONObject.parseObject(resp.parseAsString());
				boolean flag = obj.getBoolean("ok");
				if( flag ){
					return obj.getString("msg");
				}
				logger.error("storeImgThumb faild:"+obj.getString("msg"));
				return null;
			}else{
				logger.error("storeImgThumb faild:status="+statusCode+" msg="+resp.getStatusMessage());
			}
		}catch(Exception e){
			logger.error("storeImgThumb exception:",e);
		}
		return null;
	}
	
	public String storeData(String account,String base64Data,String dataType,String fileName){
		try {
			GenericUrl  url = new GenericUrl(Configurator.getInstance().getString("storeServer")+"/upload");
			url.put("utoken", account);
			url.put("type", dataType);
			url.put("file", fileName);
			base64Data = base64Data.replaceAll(" ", "+");
			ByteArrayContent content = new ByteArrayContent(ContentType.APPLICATION_OCTET_STREAM.toString(),Base64.decodeBase64(base64Data));
			HttpRequest request = requestFactory.buildPostRequest(url, content);
			com.google.api.client.http.HttpResponse resp = request.execute();
			int statusCode = resp.getStatusCode();
			if( statusCode == HttpStatus.SC_OK ){
				JSONObject obj = JSONObject.parseObject(resp.parseAsString());
				boolean flag = obj.getBoolean("ok");
				if( flag ){
					return obj.getString("msg");
				}
				logger.error("store data faild:"+obj.getString("msg"));
				return null;
			}else{
				logger.error("store data faild:status="+statusCode+" msg="+resp.getStatusMessage());
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("store data exception:",e);
		}
		return null;
		
	}
	
	public JSONObject getData(String account,String restoken){
		try{
			GenericUrl  url = new GenericUrl(Configurator.getInstance().getString("storeServer")+"/fetch");
			url.put("utoken", account);
			url.put("restoken", restoken);
			HttpRequest request = requestFactory.buildPostRequest(url, new EmptyContent() );
			HttpResponse resp = request.execute();
			int statusCode = resp.getStatusCode();
			if( statusCode == HttpStatus.SC_OK ){
				JSONObject obj = JSONObject.parseObject( resp.parseAsString() );
				boolean flag = obj.getBoolean("ok");
				if( flag ){
					return obj.getJSONObject("msg");
				}
				logger.error("fetch data faild:"+obj.getString("msg"));
				return null;
			}else{
				logger.error("fetch data faild:status="+statusCode+" msg="+resp.getStatusMessage());
			}
		}catch(Exception e){
			logger.error("fetch data exception:"+e.getMessage());
		}
		return null;
	}
	
	public JSONObject getList(String account,String token){
		try{
			GenericUrl  url = new GenericUrl(Configurator.getInstance().getString("storeServer")+"/ls");
			url.put("utoken", account);
			url.put("token", token);
			HttpRequest request = requestFactory.buildPostRequest(url, new EmptyContent() );
			HttpResponse resp = request.execute();
			int statusCode = resp.getStatusCode();
			if( statusCode == HttpStatus.SC_OK ){
				JSONObject obj = JSONObject.parseObject( resp.parseAsString() );
				boolean flag = obj.getBoolean("ok");
				if( flag ){
					obj.put("result", obj.getJSONObject("msg"));
					obj.put("msg", "" );
					return obj;
				}
				logger.error("fetch data faild:"+obj.getString("msg"));
				return null;
			}else{
				logger.error("fetch data faild:status="+statusCode+" msg="+resp.getStatusMessage());
			}
		}catch(Exception e){
			logger.error("fetch data exception:"+e.getMessage());
		}
		return null;
	}
	
	public boolean delData(String account,String restoken){
		try
		{
			GenericUrl  url = new GenericUrl(Configurator.getInstance().getString("storeServer")+"/del");
			url.put("utoken", account);
			url.put("restoken", restoken);
			HttpRequest request = requestFactory.buildPostRequest(url, new EmptyContent() );
			com.google.api.client.http.HttpResponse resp = request.execute();
			int statusCode = resp.getStatusCode();
			if( statusCode == HttpStatus.SC_OK ){
				JSONObject obj = JSONObject.parseObject(resp.parseAsString());
				boolean flag = obj.getBoolean("ok");
				if( flag ){
					return true;
				}
				logger.error("del data faild:"+obj.getString("msg"));
				return false;
			}else{
				logger.error("del data faild:status="+statusCode+" msg="+resp.getStatusMessage());
			}
		}catch(Exception e){
			logger.error("del data exception:"+e.getMessage());
		}
		return false;
	}
}
